/*package com.gzdhkj.handsetordering.pages


import android.app.Activity
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.IsoDep
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.gzdh.dishrecognition.util.TripleDESUtil
import java.io.IOException


class NfcCpuCardActivity : AppCompatActivity() {
    private var nfcAdapter: NfcAdapter? = null
    private var pendingIntent: PendingIntent? = null
    private var model: Int? = null
    private var extPwd: String? = null
    var running = true;
    private val techList = arrayOf(arrayOf(IsoDep::class.java.name))


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_nfc)
        var modelStr: String? = intent.getStringExtra("model")
        if (modelStr != null) {
            model = modelStr!!.toInt()
            extPwd = intent.getStringExtra("extPwd")
            if (model == 2) {//cpu卡
                nfcInit()
                return
            }
        }
    }

    fun nfcInit() {


        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        val intent = Intent(this, javaClass).apply {
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        }
        //获取通知
        pendingIntent = PendingIntent.getActivity(
            this, 0, intent, PendingIntent.FLAG_MUTABLE
        )


        if (nfcAdapter == null) {
            // NFC not available on this device
            Toast.makeText(this, "设备不支持NFC", Toast.LENGTH_LONG).show();
            return;
        } else {
            if (!nfcAdapter!!.isEnabled) {
                // NFC is disabled, show the settings UI
                // to enable NFC
                Toast.makeText(this, "请在系统设置中先启用NFC功能", Toast.LENGTH_SHORT).show();
                startActivity(Intent(Settings.ACTION_NFC_SETTINGS));
            }
        }
    }


    override fun onResume() {
        super.onResume()
        val filters = arrayOf(IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED))
        // foreground dispatch should be enabled here
        nfcAdapter?.enableForegroundDispatch(this, pendingIntent, filters, techList)
    }

    override fun onPause() {
        super.onPause()
        // foreground dispatch should be disabled here
        nfcAdapter?.disableForegroundDispatch(this)
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        resolveIntent(intent);
    }

    override fun onDestroy() {
        running = false;
        super.onDestroy()
        if (nfcAdapter != null) {
            nfcAdapter = null;
        }
    }

    //解析intent
    fun resolveIntent(intent: Intent?) {
        //获取intent中携带的标签对象

        if (intent != null) {

            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            if (tag != null) {
                var isoDep = IsoDep.get(tag)
                if (isoDep == null) {
                    setResult(Activity.RESULT_OK)
                    finish()
                    return;
                }
                try {
                    isoDep.connect()
                    if (!isoDep.isConnected) return

                    val authCommand = externalAuthenticate(
                        isoDep,
                        keyNumber = 0x00,  // 密钥号
                        key = hexStringToByteArray(extPwd!!) // 16字节DES密钥
                    )

                    // 处理认证响应
                    val response = isoDep.transceive(authCommand)
                    if (isSuccess(response)) {
                        val id = tag.id.reversed()
                        val hexString = ByteUtils.bytesToHexString(id);
                        val data = Intent()
                        data.putExtra("id", hexString)
                        setResult(Activity.RESULT_OK, data)
                        finish()
                    } else {
                        // 认证失败
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                } finally {
                    try {
                        isoDep.close()
                    } catch (e: IOException) {
                        // 忽略关闭异常
                    }
                }
            }

        }

    }

    fun backClick(view: View) {
        finish()
    }

// 检查APDU响应是否成功

    private fun isSuccess(response: ByteArray): Boolean {
        val code = arrayOf(
            response[response.size - 2],
            response[response.size - 1]
        ).joinToString("") { byte ->
            val value = byte.toInt() and 0xFF
            String.format("%02X", value)
        }
        var errMsg =
            when (code) {
                "6a82" -> "未找到文件"
                "6a88" -> "未找到引用数据"
                "6a80" -> "数据错误"
                "6700" -> "数据长度不正确"
                "6981" -> "命令与文件结构不相容"
                else -> ""
            }
        if (code.startsWith("63C")) {
            errMsg = "验证失败,剩余次数:${code[3].digitToInt(radix = 16)}"
        }
        if (errMsg.isNotEmpty()) {
            Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show()
        }
        return response.size >= 2 &&
                response[response.size - 2] == 0x90.toByte() &&
                response[response.size - 1] == 0x00.toByte()
    }

    fun ByteArray.toHexString() = joinToString("") { byte ->
        val value = byte.toInt() and 0xFF
        String.format("%02X", value)
    }

// 16进制字符串转字节数组

    private fun hexStringToByteArray(hex: String): ByteArray {
        val len = hex.length
        val data = ByteArray(len / 2)
        var i = 0
        while (i < len) {
            data[i / 2] = ((Character.digit(hex[i], 16) shl 4) +
                    Character.digit(hex[i + 1], 16)).toByte()
            i += 2
        }
        return data
    }

// 构建外部认证APDU命令

    private fun externalAuthenticate(isoDep: IsoDep, keyNumber: Int, key: ByteArray): ByteArray {
        // 步骤1：获取随机数（实际需替换为卡片支持的初始化命令）
        val getChallenge = byteArrayOf(0x00, 0x84.toByte(), 0x00, 0x00, 0x08)
        val challenge = isoDep.transceive(getChallenge).copyOfRange(0, 8)

        // 步骤2：用密钥加密随机数（此处简化，实际需完整加密流程）
        val encrypted = TripleDESUtil.encrypt3DES_ECB(key, challenge) // 替换为实际加密方法

        // 步骤3：发送外部认证命令
        return byteArrayOf(
            0x00, 0x82.toByte(), 0x00, keyNumber.toByte(), 0x08,  // CLA, INS, P1, P2, Lc
            *encrypted,                                  // 加密数据
            0x00                                         // Le
        )
    }

}*/
